<template>
  <basic-container>
    <avue-crud
      :option="option"
      :search.sync="search"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @sort-change="sortChange"
      @on-load="onLoad"
    >
      <template slot-scope="scope" slot="menu">
        <!-- <el-button icon="el-icon-view" size="small" type="text" @click.stop="handleAudit(scope.row, scope.index)">审 核</el-button> -->
        <el-button icon="el-icon-edit" size="small" type="text" v-if="scope.row.adminState == 2" @click.stop="handleEdit(scope.row, scope.index)">编 辑</el-button>
        <el-button icon="el-icon-edit" size="small" type="text" @click.stop="handleDetails(scope.row, scope.index)">详 情</el-button>
      </template>
      <template slot="menuLeft">
        <el-button type="primary" icon="el-icon-edit-outline" size="small" @click.stop="handleAlter">变 更</el-button>
        <!-- <el-button
          type="danger"
          size="small"
          icon="el-icon-delete"
          plain
          v-if="permission.mer_change_record_delete"
          @click="handleDelete"
          >删 除
        </el-button> -->
      </template>
      <!-- <template slot="menuRight">
        <el-button
          type="success"
          size="small"
          plain
          icon="el-icon-upload2"
          v-if="permission.mer_change_record_import"
          @click="handleImport"
          >导入
        </el-button>
        <el-button
          type="warning"
          size="small"
          plain
          icon="el-icon-download"
          v-if="permission.mer_change_record_export"
          @click="handleExport"
          >导出
        </el-button>
      </template> -->
      <template slot-scope="{row}"
            slot="accountManager">
        <span>{{row.accountManagerName}}</span>
      </template>
      <template slot-scope="{row}"
                slot="adminState">
        <el-tag type="success" :color="getColorRpiExStatus(row.adminState)" effect="dark">{{ row.adminStateName?row.adminStateName:'未提交' }}</el-tag>
      </template>
    </avue-crud>
    <el-dialog
      :title="dialogText+' 商户信息'"
      :width="screenWidth>1920?'50%':(screenWidth<=1920 && screenWidth>1500)?'66%':'80%'"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      :before-close="handleClose">
      <template>
        <!-- <div class="merchant-padding" v-if="dialogType === 'edit'">
          <auditForm :auditForm="auditForm" :rejectList="rejectList" :isReject="true" ref="toAuditForm" />
        </div> -->
        <div class="merchant-padding" v-if="dialogType === 'edit'">
          <audit-record :rejectRecord="rejectRecord" ref="toAuditRecord" />
        </div>
        <!-- <alter-form :isAlterDisabledShow="isAlterDisabledShow" @getDetailReject="getDetailReject" ref="toAlterForm" /> -->
        <alter-form :isAlterDisabledShow="isAlterDisabledShow" :isAlterShow="true" ref="toAlterForm" />
      </template>
      <span slot="footer" class="dialog-footer">
        <el-button icon="el-icon-close" size="small" @click="handleCancel">取 消</el-button>
        <el-button icon="el-icon-check" size="small" type="primary" v-preventClick @click="handleConfirm">提 交</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="数据导入"
      append-to-body
      :visible.sync="excelBox"
      width="555px"
    >
      <avue-form
        :option="excelOption"
        v-model="excelForm"
        :upload-after="uploadAfter"
      >
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleTemplate">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
    </el-dialog>
  </basic-container>
</template>

<script>
import {
  getList,
  getDetail,
  add,
  update,
  // addMerRecord,
  updateMerRecord,
  remove,
} from "@/api/rb-service/merrecord/mer_change_record";
import { mapGetters } from "vuex";
import { getToken } from "@/util/auth";
import alterForm from '@/components/rb-merchant/alter-form.vue';
import auditRecord from "@/components/rb-merchant/audit-record.vue";

export default {
  components: {
    alterForm,
    auditRecord
  },
  data() {
    return {
      form: {},
      query: {},
      search: {},
      screenWidth: document.documentElement.clientWidth,
      dialogVisible: false,
      dialogType: '', //打开类型 add/edit
      dialogText: '',
      isAlterDisabledShow: false, //是否禁止 alter组件内容
      loading: true,
      excelBox: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      option: {
        height: "calc(50vh - 50px)",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        selection: true,
        searchMenuSpan: 6,
        columnBtn: false,
        column: [
          // {
          //   label: "主键",
          //   prop: "id",
          //   type: "input",
          //   //sortable: true,
          // },
          {
            label: "商户号",
            prop: "rpiNo",
            type: "input",
            //sortable: true,
            overHidden: true,
            minWidth:140
          },
          {
            label: "门头名称",
            prop: "rpiName",
            type: "input",
            width: 200,
            search: true,
            overHidden: true
          },
          // {
          //   label: "客户经理",
          //   prop: "accountManager",
          //   type: "select",
          //   dicUrl: "/api/rb-service/service/posinfo/pos_info/accountManagerList?createUser={{key}}",
          //   props: {
          //     label: "userName",
          //     value: "userId",
          //   },
          //   dataType: "string",
          //   showColumn: false,
          //   search: true,
          //   rules: [
          //     {
          //       required: true,
          //       message: "请输入审核状态",
          //       trigger: "blur",
          //     },
          //   ],
          //   overHidden: true,
          // },
          {
            label: "服务商名称",
            prop: "serveName",
            type: "input",
            search: true,
            width: 200,
            overHidden: true
          },
          {
            label: "变更类型",
            prop: "changeType",
            type: "select",
            //sortable: true,
            search: true,
            dataType: "number",
            showColumn: false,
            slot: true,
            dicUrl: '/api/blade-system/dict/dictionary?code=change_type',
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            overHidden: true,
          },
          // {
          //   label: "变更描述",
          //   prop: "remark",
          //   type: "input",
          // },
          {
            label: "提交日期",
            prop: "submitDate",
            type: "input",
            overHidden: true,
            width:140
          },
          {
            label: "审核结果",
            prop: "adminState",
            type: "select",
            //sortable: true,
            search: true,
            dataType: "number",
            showColumn: false,
            slot: true,
            dicUrl: '/api/blade-system/dict/dictionary?code=admin_state',
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            overHidden: true,
            width:100
          },
          {
            label: "审核备注",
            prop: "adminResult",
            width: 150,
            overHidden:true,
            span: 24,
            addDisplay: false,
            editDisplay: false,
          }
        ],
      },
      data: [],
      alterForm: {},
      auditForm: {
        auditSuccess: "2",
        auditType: "",
        auditReason: "",
        auditWay: "",
      },
      rejectList: [],
      rejectRecord: {},
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "模板上传",
            prop: "excelFile",
            type: "upload",
            drag: true,
            loadText: "模板上传中，请稍等",
            span: 24,
            propsHttp: {
              res: "data",
            },
            tip: "请上传 .xls,.xlsx 标准格式文件",
            action: "/api/rb-service/service/merrecord/mer_change_record/import",
          },
          {
            label: "模板下载",
            prop: "excelTemplate",
            formslot: true,
            span: 24,
          },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.mer_change_record_add, false),
        viewBtn: this.vaildData(this.permission.mer_change_record_view, false),
        delBtn: this.vaildData(this.permission.mer_change_record_delete, false),
        editBtn: this.vaildData(this.permission.mer_change_record_edit, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    getColorRpiExStatus() {
      return state => {
        if (state == '0') {
          return '#E6A23C';
        } else if (state == '1') {
          return '#67C23A';
        } else if (state == '2') {
          return '#F56C6C';
        } else if (state == '3') {
          return '#396afc';
        } else if (state == '4') {
          return '#F56C6C';
        } else {
          return '#8e9eab';
        }
      }
    }
  },
  methods: {
    /**
     * @func dialog商户信息确认
     * @desc dialog商户信息(变更/修改)确认
     * */
    handleConfirm() {
      if (this.dialogType == 'add') {
        this.$refs['toAlterForm'].$refs['alterForm'].validate((valid) => {
          if (valid) {
            this.dialogVisible = false;
            this.$router.push({
              name: "商户变更",
              query: {
                rpiNo: this.$refs['toAlterForm'].alterForm.rpiNo,
                changeType: this.$refs['toAlterForm'].alterForm.changeType,
                aisleCode: this.$refs['toAlterForm'].alterForm.aisleCode
              }
            });
            this.emptyForm();
            // if (this.$refs['toAlterForm'].alterForm.changeType == "1") {
            //   [this.$refs['toAlterForm'].alterForm.cardDTO.openAccProvinceCode, this.$refs['toAlterForm'].alterForm.cardDTO.openAccCityCode, this.$refs['toAlterForm'].alterForm.cardDTO.openAccAreaCode] = this.$refs['toAlterForm'].alterForm.cardDTO.accProvinceCityArea;
            // }
            // addMerRecord(this.$refs['toAlterForm'].alterForm).then(
            //   (res) => {
            //     if (res.data.code === 200) {
            //       this.onLoad(this.page);
            //       this.$message({
            //         type: "success",
            //         message: "操作成功!",
            //       });
            //       this.dialogVisible = false;
            //       this.emptyForm();
            //     }
            //   },(error) => {
            //     window.console.log(error);
            //   }
            // );
          } else {
            return false;
          }
        });
      } else if (this.dialogType == 'edit') {
        this.$refs['toAlterForm'].$refs['alterForm'].validate((valid) => {
          if (valid) {
            if (this.$refs['toAlterForm'].alterForm.changeType == "1") {
              [this.$refs['toAlterForm'].alterForm.cardDTO.openAccProvinceCode, this.$refs['toAlterForm'].alterForm.cardDTO.openAccCityCode, this.$refs['toAlterForm'].alterForm.cardDTO.openAccAreaCode] = this.$refs['toAlterForm'].alterForm.cardDTO.accProvinceCityArea;
            }
            updateMerRecord(this.$refs['toAlterForm'].alterForm).then(
              (res) => {
                if (res.data.code === 200) {
                  this.onLoad(this.page);
                  this.$message({
                    type: "success",
                    message: "操作成功!",
                  });
                  this.dialogVisible = false;
                  this.emptyForm();
                }
              },(error) => {
                window.console.log(error);
              }
            );
          } else {
            return false;
          }
        });
      }
      
    },
    /**
     * @func dialog商户信息取消
     * @desc dialog商户信息(变更/修改)取消
     * */
    handleCancel() {
      this.dialogVisible = false;
      this.emptyForm();
    },
    /**
     * @func 变更
     * @desc 点击变更初始化显示商户信息
     * */
    handleAlter() {
      this.active = 0;
      this.dialogVisible = true;
      this.isAlterDisabledShow = false;
      this.dialogType = 'add';
      this.dialogText = '新增变更';
      // this.$router.push({
      //   name: "商户变更"
      // });
    },
    /**
     * @func 编辑
     * @desc 点击编辑回显基本信息
     * @param {Object} row - 商户信息
     * */
    handleEdit(row) {
      this.dialogType = 'edit';
      this.$router.push({
        name: "变更驳回编辑",
        query: {
          changeNo: row.changeNo,
        }
      });
      // this.active = 0;
      // this.dialogVisible = true;
      // this.isAlterDisabledShow = true;
      // this.dialogType = 'edit';
      // this.dialogText = '编辑变更';
      // this.$nextTick(() => {
      //   this.$refs['toAlterForm'].getMerhchantDetailPlus(row.changeNo);
      // });
    },
    /**
     * @func 商户变更详情
     * @desc 点击详情跳转商户变更详情页面
     * @param {Object} row - 商户信息
     * */
    handleDetails(row) {
      this.$router.push({
        name: "商户变更详情",
        query: {
          changeNo: row.changeNo,
        }
      });
    },
    // /**
    //  * @func 审核
    //  * @desc 点击审核进入审核页
    //  * @param {Object} row - 商户信息
    //  * */
    // handleAudit(row) {
    //   this.$router.push({
    //     name: "变更审核",
    //     query: {
    //       id: row.id
    //     }
    //   });
    // },
    /**
     * @func 关闭弹窗
     * @desc 点击关闭的回调
     * @param {Function} done - 完成回调
     * */
    handleClose(done) {
      this.emptyForm();
      done();
    },
    /**
     * @func 清空
     * @desc OEM表单信息 清空
     * */
    emptyForm() {
      this.$refs['toAlterForm'].$refs['alterForm'].resetFields();
      // this.$refs["toAlterForm"].basicForm = {};
      // this.$refs["toAlterForm"].accountFrontList = [];
      // this.$refs['toAlterForm'].accountReverseList = [];
      // this.$refs['toAlterForm'].openPermitList = [];
      // this.$refs['toAlterForm'].ecardFrontList = [];
      // this.$refs['toAlterForm'].ecardReverseList = [];
      // this.$refs['toAlterForm'].changeApplyPicList = [];
    },
    /* 编辑时 dialog回显驳回的记录 */
    getDetailReject(data) {
      // this.rejectList = list;
      this.rejectRecord = data;
    },
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    handleImport() {
      this.excelBox = true;
    },
    handleExport() {
      let exQuery = ``;
      exQuery += `&rpiNo=${this.search.rpiNo}`;
      exQuery += `&changeType=${this.search.changeType}`;
      this.$confirm("是否导出用户数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        window.open(
          `/api/rb-service/service/merrecord/mer_change_record/export?${
            this.website.tokenHeader
          }=${getToken()}` + exQuery
        );
      });
    },
    handleTemplate() {
      window.open(
        `/api/rb-service/service/merrecord/mer_change_record/export-template?${
          this.website.tokenHeader
        }=${getToken()}`
      );
    },
    uploadAfter(res, done) {
      this.excelBox = false;
      this.refreshChange();
      done();
    },
    sortChange(val) {
      if (val.order == "ascending") {
        //正序
        this.query.ascs = val.prop;
        this.query.descs = "";
      } else {
        //倒序
        this.query.descs = val.prop;
        this.query.ascs = "";
      }
      this.refreshChange();
    },
  },
};
</script>

<style lang="scss" scoped>
.merchant-padding {
  padding: 20px;
}

/deep/ .el-tag--dark.el-tag--success {
  border-color: transparent;
  opacity: 0.8;
}
</style>
